package com.wwtech.epp.ui.activity.work;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.ninjia.ninjiabaselibrary.view.RxDialogWheelYearMonthDayMe;
import com.socks.library.KLog;
import com.wwtech.epp.R;
import com.wwtech.epp.application.AppConfig;
import com.wwtech.epp.base.BaseActivity;
import com.wwtech.epp.contain.ContainValue;
import com.wwtech.epp.db.Friend;
import com.wwtech.epp.entity.ProjectTask;
import com.wwtech.epp.ui.activity.friend.AddManagerActivity;
import com.wwtech.epp.ui.activity.friend.AddPersonActivity;
import com.wwtech.epp.ui.activity.work.component.DaggerNewProjectComponent;
import com.wwtech.epp.ui.activity.work.contract.NewProjectContract;
import com.wwtech.epp.ui.activity.work.module.NewProjectModule;
import com.wwtech.epp.ui.activity.work.presenter.NewProjectPresenter;
import com.wwtech.epp.ui.adapter.work.ProjectAdapter;
import com.wwtech.epp.ui.adapter.work.ProjectTaskAdapter;
import com.wwtech.epp.utils.StringUitl;
import com.wwtech.epp.utils.ToastUtil;
import com.wwtech.epp.view.GlideCircleTransform;
import com.wwtech.epp.view.ProjectMemberView;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import javax.inject.Inject;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

import static com.wwtech.epp.R.id.cancal;
import static com.wwtech.epp.R.id.sure;

/**
 * @author hzp
 * @Package com.wwtech.epp.ui.activity.work
 * @Description: $description
 * @date 2017/09/01 22:09:47
 */

public class NewProjectActivity extends BaseActivity implements NewProjectContract.View {

    @Inject
    NewProjectPresenter mPresenter;
//    ProjectAdapter projectAdapter;         //负责人的adapter

    ProjectAdapter partMamberAdapter;      //参与人的adapter
    @Inject
    ProjectTaskAdapter projectTaskAdapter; //添加的任务的adapter

    @BindView(R.id.textView)
    TextView textView;
    //    @BindView(R.id.recycerView_manager)
//    RecyclerView recycerViewManager;
    @BindView(R.id.recycerView_part)
    RecyclerView recycerViewPart;
    @BindView(R.id.recycerView_task)
    RecyclerView recycerViewTask;
    @BindView(R.id.add_task)
    TextView addTask;
    @BindView(R.id.new_project)
    TextView newProject;

    public static final int CHECKMANAGE = 1;
    public static final int CHECKPART = 2;
    public static final int CHECKTASKMANAGE = 3;
    public static final int RESULTOK = 20;
    @BindView(R.id.project_member_view)
    ProjectMemberView projectMemberView;
    @BindView(R.id.et_project_name)
    EditText etProjectName;
    @BindView(R.id.et_project_targe)
    EditText etProjectTarge;
    @BindView(R.id.et_project_desc)
    EditText etProjectDesc;
    @BindView(R.id.tv_project_start_time)
    TextView tvProjectStartTime;
    @BindView(R.id.project_endt_time)
    TextView projectEndtTime;
    private RxDialogWheelYearMonthDayMe mRxDialogWheelYearMonthDay;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    protected void initView() {
        setContentView(R.layout.activity_new_project);
        ButterKnife.bind(this);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    }

    @Override
    protected void initData() {
        mPresenter.init();
        setTitle("新建项目");
        GridLayoutManager gm = new GridLayoutManager(this, 5);
        GridLayoutManager gm1 = new GridLayoutManager(this, 5);
        GridLayoutManager gm2 = new GridLayoutManager(this, 1);
//        recycerViewManager.setLayoutManager(gm);
        recycerViewPart.setLayoutManager(gm1);
        recycerViewTask.setLayoutManager(gm2);
        projectTaskAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter baseQuickAdapter, View view, int i) {
                switch (view.getId()) {
                    case R.id.iv_avater:
                        Intent intent = new Intent(NewProjectActivity.this, AddManagerActivity.class);
                        intent.putExtra("position", i + "");
                        startActivityForResult(intent, NewProjectActivity.CHECKTASKMANAGE);
                        break;
                    case R.id.tv_end_time:
                        initWheelYearMonthDayDialog(1, i);
                        mRxDialogWheelYearMonthDay.show();
                        break;
                    case R.id.tv_task_desc:
                        showEditTaskDescDialog(i);
                        break;
                }
            }
        });
        recycerViewTask.setAdapter(projectTaskAdapter);
//        recycerViewManager.setNestedScrollingEnabled(false);
        recycerViewPart.setNestedScrollingEnabled(false);
        recycerViewTask.setNestedScrollingEnabled(false);

        Friend friend = new Friend(ContainValue.userLogin.getData().getUserId() + "", ContainValue.userLogin.getData().getNickName(), Uri.parse(ContainValue.userLogin.getData().getAvatar()));
        friend.setAvatar(ContainValue.userLogin.getData().getAvatar());
        friend.setNickname(ContainValue.userLogin.getData().getNickName());
        friend.setUserId(ContainValue.userLogin.getData().getUserId() + "");
        ContainValue.projectManager = friend;
        onProjectManagerBack(friend);
    }

    private void showEditTaskDescDialog(int position) {
        AlertDialog alertDialog1 = new AlertDialog.Builder(this).create();
        View view2 = View.inflate(this, R.layout.edit_task_desc_dialog, null);
        alertDialog1.setView(view2);
        alertDialog1.setCancelable(true);
        EditText tv_title1 = (EditText) view2.findViewById(R.id.content);
        TextView cancal1 = (TextView) view2.findViewById(cancal);
        TextView sure1 = (TextView) view2.findViewById(sure);
        cancal1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                alertDialog1.dismiss();
            }
        });
        sure1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                projectTaskAdapter.getData().get(position).setDiscrab(tv_title1.getText().toString().trim());
                projectTaskAdapter.notifyDataSetChanged();
                alertDialog1.dismiss();
            }
        });
        alertDialog1.show();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        mPresenter.onActivityResult(requestCode, resultCode, data);
    }

    @Override
    protected void setupActivityComponent() {
        DaggerNewProjectComponent
                .builder()
                .appComponent(((AppConfig) getApplication()).getApplicationComponent())
                .newProjectModule(new NewProjectModule(this))
                .build()
                .inject(this);
    }

    @Override
    public void setPresenter(NewProjectContract.NewProjectContractPresenter presenter) {
        mPresenter = (NewProjectPresenter) presenter;
    }

    @Override
    public void showProgressDialog() {
        progressDialog.show();
    }

    @Override
    public void closeProgressDialog() {
        progressDialog.hide();
    }

    @Override
    public void setProjectTaskData(ArrayList<ProjectTask> list) {
        projectTaskAdapter.setNewData(list);
    }

    @Override
    public void setPersonData(ArrayList<Friend> managerList, ArrayList<Friend> partList) {
        if (partMamberAdapter == null) {
            partMamberAdapter = new ProjectAdapter(partList);
            recycerViewPart.setAdapter(partMamberAdapter);
            partMamberAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
                @Override
                public void onItemChildClick(BaseQuickAdapter baseQuickAdapter, View view, int i) {
                    ProjectMemberView projectMemberView = (ProjectMemberView) view;
                    if (projectMemberView.isSetInfo()) {
                        ContainValue.partPerson.remove(i);
                        partMamberAdapter.notifyDataSetChanged();
                    } else {
                        ContainValue.partPerson = (ArrayList<Friend>) partMamberAdapter.getData();
                        Intent intent = new Intent(NewProjectActivity.this, AddPersonActivity.class);
                        intent.putExtra("title", "选择参与人");
                        startActivityForResult(intent, CHECKPART);
                    }
                }
            });
        }
        partMamberAdapter.setNewData(partList);
    }

    @Override
    public void onProjectManagerBack(Friend friend) {
        projectMemberView.getNickTextview().setText(friend.getNickname());
        projectMemberView.setSetInfo(true);
        Glide.with(this)
                .load(friend.getAvatar())
                .transform(new GlideCircleTransform(this))
                .into(projectMemberView.getAvaterImg());
    }

    @Override
    public void onProjectTaskManagerBaack() {
        projectTaskAdapter.notifyDataSetChanged();
    }

    @OnClick({R.id.add_task, R.id.new_project, R.id.project_member_view, R.id.tv_project_start_time, R.id.project_endt_time})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.add_task:
                mPresenter.addProjectTask();
                break;
            case R.id.new_project:
                projectTaskAdapter.notifyDataSetChanged();
                checkInfo();
                break;
            case R.id.project_member_view:
                Intent intent = new Intent(this, AddManagerActivity.class);
                intent.putExtra("position", "-1");
                startActivityForResult(intent, NewProjectActivity.CHECKMANAGE);
                break;
            case R.id.tv_project_start_time:
                initWheelYearMonthDayDialog(0, 0);
                mRxDialogWheelYearMonthDay.show();
                break;
            case R.id.project_endt_time:
                initWheelYearMonthDayDialog(0, 1);
                mRxDialogWheelYearMonthDay.show();
                break;
        }
    }

    @Override
    public void onBackPressed() {
        finish();
        overridePendingTransition(0, R.anim.activity_translate_out_1);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        ContainValue.projectManager = null;
        ContainValue.partPerson = null;
    }

    private void checkInfo() {
        if (StringUitl.isNotEmpty(etProjectName, "请输入项目名称") && StringUitl.isNotEmpty(etProjectTarge, "请输入项目目标") && StringUitl.isNotEmpty(etProjectDesc, "请输入项目描述")) {
            if (StringUitl.isNotEmpty(tvProjectStartTime, "请选择项目开始时间") && StringUitl.isNotEmpty(projectEndtTime, "请选择项目结束时间")) {
                if (ContainValue.projectManager == null) {
                    ToastUtil.displayShortToast("请选择项目负责人");
                    return;
                }
                if (ContainValue.partPerson == null || ContainValue.partPerson.size() == 0) {
                    ToastUtil.displayShortToast("请选择项目参与人");
                    return;
                }
                for (int i = 0; i < projectTaskAdapter.getData().size(); i++) {
                    if (projectTaskAdapter.getData().get(i).getDiscrab().equals("")) {
                        ToastUtil.displayShortToast("请输入第" + (i + 1) + "个任务的任务描述");
                        return;
                    }
                    if (projectTaskAdapter.getData().get(i).getEndTime().equals("")) {
                        ToastUtil.displayShortToast("请选择第" + (i + 1) + "个任务的结束时间");
                        return;
                    }
                    if (!projectTaskAdapter.getData().get(i).isCheck()) {
                        ToastUtil.displayShortToast("请选择第" + (i + 1) + "个任务的负责人");
                        return;
                    }
                }
                packData();

            }

        }
    }

    /**
     * {
     "beginTime": "2017-09-14T14:43:09.117Z",
     "endTime": "2017-09-14T14:43:09.117Z",
     "ownerUid": 0,
     "partner": [
     0
     ],
     "projectDesc": "string",
     "projectName": "string",
     "projectTarget": "string",
     "subJob": [
     {
     "createTime": "2017-09-14T14:43:09.117Z",
     "createrId": 0,
     "deadline": "2017-09-14T14:43:09.117Z",
     "jobContent": "string",
     "jobId": 0,
     "jobState": 0,
     "jobTitle": "string",
     "ownerId": 0,
     "projectId": 0,
     "state": 0
     }
     ]
     }
     * 包装数据
     */
    private void packData() {
        KLog.i("准备数据");
        Map<String, Object> map = new HashMap<>();
        map.put("beginTime",tvProjectStartTime.getText().toString().trim());
        map.put("endTime",projectEndtTime.getText().toString().trim());
        map.put("projectDesc",etProjectDesc.getText().toString().trim());
        map.put("projectName",etProjectName.getText().toString().trim());
        map.put("projectTarget",etProjectTarge.getText().toString().trim());
        mPresenter.packData(map);
    }

    private void initWheelYearMonthDayDialog(int type, int postion) {
        // ------------------------------------------------------------------选择日期开始
        mRxDialogWheelYearMonthDay = new RxDialogWheelYearMonthDayMe(this, 0, 0);
        mRxDialogWheelYearMonthDay.getTv_sure().setOnClickListener(
                new View.OnClickListener() {
                    @Override
                    public void onClick(View arg0) {
                        String time = mRxDialogWheelYearMonthDay.getSelectorYear() + "-" + mRxDialogWheelYearMonthDay.getSelectorMonth() + "-" + mRxDialogWheelYearMonthDay.getSelectorDay() + "";
                       if (type == 0) {
                           if (postion == 0) {
                                tvProjectStartTime.setText(time);
                           }
                           if (postion == 1) {
                               projectEndtTime.setText(time);
                           }
                       }
                       if (type == 1) {
                           projectTaskAdapter.getData().get(postion).setEndTime(time);
                           projectTaskAdapter.notifyDataSetChanged();
                       }
                        mRxDialogWheelYearMonthDay.cancel();
                    }
                });
        mRxDialogWheelYearMonthDay.getTv_cancle().setOnClickListener(
                new View.OnClickListener() {

                    @Override
                    public void onClick(View arg0) {
                        mRxDialogWheelYearMonthDay.cancel();
                    }
                });
        // ------------------------------------------------------------------选择日期结束
    }

}